/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sms4j.util;

import flexjson.JSONSerializer;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import sms4j.entity.ShortMessage;

/**
 *
 * @author Swang
 */
public class SmsUtil {

    private static final Logger logger = Logger.getLogger(SmsUtil.class.getName());
    private static Pattern MOBILE_PHONE_PATTERN = Pattern.compile("^(1[0-9][0-9])\\d{8}$");

    public static String sendMessage(String toPhoneNumber, String message, String serviceSocketIP, int serviceSocketPort, String outEncode) {
        return sendMessage(new ShortMessage(toPhoneNumber, message), serviceSocketIP, serviceSocketPort, outEncode);
    }

    public static String sendMessage(ShortMessage shortMessage, String serviceSocketIP, int serviceSocketPort, String outEncode) {
        BufferedReader socketReader = null;
        PrintWriter socketWriter = null;
        Socket client = null;
        try {
            String toPhoneNumber = shortMessage.getToPhoneNumber();
            if (toPhoneNumber == null || toPhoneNumber.trim().equals("")) {
                return "Send Message Fail, toPhoneNumber can't null";
            }
            if (!isMobilePhoneNumber(toPhoneNumber)) {
                return "Send Message Fail, toPhoneNumber style invalid";
            }
            client = new Socket(serviceSocketIP, serviceSocketPort);
            socketReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            socketWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream(), outEncode)), true);
            String jsonData = new JSONSerializer().serialize(shortMessage);
            logger.log(Level.INFO, "Output :{0}", jsonData);
            socketWriter.println(jsonData);
            socketWriter.println("EOF");
            socketWriter.flush();
            StringBuilder result = new StringBuilder();
            String line = null;
            while ((line = socketReader.readLine()) != null) {
                result.append(line);
            }

            return result.toString();
        } catch (Exception ex) {
            Logger.getLogger(SmsUtil.class.getName()).log(Level.SEVERE, null, ex);
            return "Exception send message";
        } finally {
            if (null != socketWriter) {
                socketWriter.close();
                socketWriter = null;
            }
            if (null != socketReader) {
                try {
                    socketReader.close();
                } catch (IOException ex) {
                    Logger.getLogger(SmsUtil.class.getName()).log(Level.SEVERE, null, ex);
                }
                socketReader = null;
            }
            if (null != client) {
                try {
                    client.close();
                } catch (IOException ex) {
                    Logger.getLogger(SmsUtil.class.getName()).log(Level.SEVERE, null, ex);
                }
                client = null;
            }
        }
    }

    public static boolean isMobilePhoneNumber(String src) {
        Matcher m1 = MOBILE_PHONE_PATTERN.matcher(src);
        return m1.matches();
    }

    public static void main(String[] args) {
        System.out.println(SmsUtil.sendMessage("13641346272", "测试测试", "192.168.1.100", 5001, "utf-8"));

    }
}
